package com.wuba.rxjavademo.lyz;

import java.util.concurrent.TimeUnit;

import rx.Observable;

/**
 * Created by liyaxing on 2016/4/16.
 */
public class Demo05 {

    public static void main(String[] ss){

        Demo05 demo05 = new Demo05() ;
//        Observable<Integer> observable1 = demo05.onExceptionResumeObserver(true) ;
//        observable1.subscribe(integer -> {
//            System.out.println("onExceptionResumeObserver true - num : " + integer) ;
//        }) ;
        Observable<Integer> observable = demo05.retryWhenObservable();
        observable.subscribe(integer -> {
            System.out.println("num : " + integer) ;
        }) ;


        try {
            Thread.sleep(100000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


    private Observable<Integer> retryWhenObservable(){
        return createObservable().retryWhen(observable -> observable.zipWith(Observable.just(1, 2, 3),
                (throwable, integer) -> throwable.getMessage() + integer)
                .flatMap(throwable -> {
                    return Observable.timer(1, TimeUnit.SECONDS);
                }));
    }

    private Observable<Integer> retryObservable(){
        return createObservable().retry(2) ;
    }

    private Observable<Integer> onExceptionResumeObserver(boolean isException){
        return createObservable(isException).onExceptionResumeNext(Observable.just(11,22,33)) ;
    }


    private Observable<Integer> onErrorReturnObservable(){
        return createObservable().onErrorReturn(throwable -> {
            return 8 ;
        }) ;
    }

    private Observable<Integer> onErrorResumeNextObservable(){
        return createObservable().onErrorResumeNext(Observable.just(1, 1, 1, 1, 1, 1, 1, 1)) ;
    }

    private Observable<Integer> createObservable(boolean isException){
        return Observable.create(subscriber -> {

            for (int i = 0; i < 10; i++) {
                if (i == 8) {
                    if(isException){
                        subscriber.onError(new Exception("value = 8"));
                    }else{
                        subscriber.onError(new Throwable("value = 8"));
                    }
                } else {
                    subscriber.onNext(i);
                }
            }
            subscriber.onCompleted();

        }) ;
    }

    private Observable<Integer> createObservable(){
        return Observable.create(subscriber -> {

            for (int i = 0; i < 10; i++) {
                if(i == 8){
                    subscriber.onError(new Throwable("value = 8"));
                }else if(i == 7){
                    subscriber.onError(new Throwable("value = 7"));
                }else if(i == 6){
                    subscriber.onError(new Throwable("value = 6"));
                }else{
                    subscriber.onNext(i);
                }
            }
            subscriber.onCompleted();

        }) ;
    }


}
